package com.uniledger.exchange.wallet;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.orhanobut.logger.Logger;
import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.stellar.sdk.KeyPair;

import java.security.SecureRandom;

import butterknife.BindView;
import butterknife.OnClick;
import io.github.novacrypto.bip32.ExtendedPrivateKey;
import io.github.novacrypto.bip32.ExtendedPublicKey;
import io.github.novacrypto.bip32.networks.Bitcoin;
import io.github.novacrypto.bip39.MnemonicGenerator;
import io.github.novacrypto.bip39.SeedCalculator;
import io.github.novacrypto.bip39.Words;
import io.github.novacrypto.bip39.wordlists.English;
import io.github.novacrypto.bip44.AddressIndex;
import io.github.novacrypto.bip44.BIP44;

/**
 * https://github.com/westonal/NovaCryptoAddressExample
 * https://github.com/EbenezerGH/bip-44-address-generator
 * https://github.com/LOOIS-IO/loois-android-sdk
 * https://github.com/Adamant-im/adamant-android
 * https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0005.md
 * https://www.stellar.org/developers/guides/get-started/create-account.html
 */
public class CreateWalletActivity extends BaseActivity {

    LoadingDialog ld;

    @BindView(R.id.btn_mnemonic_ok)
    Button btnMnemonic;

    @BindView(R.id.edit_wallet_name)
    EditText name;

    @BindView(R.id.edit_wallet_passphrase)
    EditText passphrase;

    @BindView(R.id.edit_wallet_re_passphrase)
    EditText rePassphrase;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, CreateWalletActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //TODO 防止屏幕截图在助记词操作页面
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        setContentView(R.layout.activity_create_wallet);
    }

    @OnClick(R.id.btn_mnemonic_ok)
    public void generateMnemonic() {

        String nameStr = name.getText().toString();//钱包名称
        String pwd = passphrase.getText().toString();//钱包口令
        String repwd = rePassphrase.getText().toString();

        if (!TextUtils.isEmpty(nameStr) && !TextUtils.isEmpty(pwd) && TextUtils.equals(pwd, repwd)) {
            new KeyTask().execute(nameStr, pwd);
        } else {
            //TODO 输入错误提示信息
        }
    }

    class KeyTask extends AsyncTask<String, Integer, WalletKey> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected WalletKey doInBackground(String... strings) {
            String mnemonic = generateNewMnemonic(Words.TWELVE);
            String nameStr = strings[0];
            String pwd = strings[1];

            //助记词+口令
            final byte[] seed = new SeedCalculator().calculateSeed(mnemonic, pwd);

            KeyPair keyPair = KeyPair.fromSecretSeed(seed);
            Logger.d(new String(keyPair.getSecretSeed()));
            Logger.d(keyPair.getAccountId());
            Logger.d(keyPair.getPublicKey());


            ExtendedPrivateKey root = ExtendedPrivateKey.fromSeed(seed, Bitcoin.MAIN_NET);
            AddressIndex addressIndex = BIP44
                    .m()
                    .purpose44()
                    .coinType(148)
                    .account(1)
                    .external()
                    .address(5);

            ExtendedPrivateKey child = root.derive(addressIndex.toString());
            ExtendedPublicKey childPub = child.neuter();

            //TODO
            WalletKey walletKey = new WalletKey(nameStr, mnemonic, pwd);
            walletKey.uid = 123;

            //TODO 密钥数据存入数据库
            walletKey.id = UniApp.getDb().keyDao().insert(walletKey);

            //TODO 管理员状态，已创建密钥
            UniApp.getDb().adminDao().update(123, 2);

            return walletKey;
        }

        @Override
        protected void onPostExecute(WalletKey key) {
            super.onPostExecute(key);
            MnemonicActivity.start(CreateWalletActivity.this, key);
        }
    }

    private static String generateNewMnemonic(Words wordCount) {
        StringBuilder sb = new StringBuilder();
        byte[] entropy = new byte[wordCount.byteLength()];
        new SecureRandom().nextBytes(entropy);
        new MnemonicGenerator(English.INSTANCE)
                .createMnemonic(entropy, sb::append);
        return sb.toString();
    }

    @Override
    public void getParams() {

    }

    @Override
    public void onBackPressed() {
        HomeActivity.start(this);
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
